import 'package:elephant_fish/http/core/hi_error.dart';
import 'package:elephant_fish/http/core/hi_net.dart';
import 'package:elephant_fish/http/request/base_request.dart';
import 'package:elephant_fish/http/request/order_list_request.dart';
import 'package:elephant_fish/model/order.dart';
import 'package:elephant_fish/model/order_entity.dart';
import 'package:elephant_fish/util/TxUtils.dart';
import 'package:elephant_fish/util/color.dart';
import 'package:elephant_fish/util/size_util.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'login_page.dart';

class SettingOrderPage extends StatefulWidget {
  const SettingOrderPage({Key key}) : super(key: key);

  @override
  _SettingOrderPageState createState() => _SettingOrderPageState();
}

class _SettingOrderPageState extends State<SettingOrderPage> {
  List<DataColumn> dataColumns = [
    DataColumn(
      label: Text(
        '订单号',
        style: TextStyle(fontSize: SizeUtil.px(26), color: Color(0xffffffff)),
      ),
    ),
    DataColumn(
      label: Text('礼物名称',
          style:
              TextStyle(fontSize: SizeUtil.px(26), color: Color(0xffffffff))),
    ),
    DataColumn(
      label: Text('礼物数量',
          style:
              TextStyle(fontSize: SizeUtil.px(26), color: Color(0xffffffff))),
    ),
    DataColumn(
      label: Text('价值金币',
          style:
              TextStyle(fontSize: SizeUtil.px(26), color: Color(0xffffffff))),
    ),
    DataColumn(
      label: Text('订单类型名称',
          style:
              TextStyle(fontSize: SizeUtil.px(26), color: Color(0xffffffff))),
    ),
    DataColumn(
      label: Text('收款人名称',
          style:
              TextStyle(fontSize: SizeUtil.px(26), color: Color(0xffffffff))),
    ),
    DataColumn(
      label: Text('订单状态',
          style:
              TextStyle(fontSize: SizeUtil.px(26), color: Color(0xffffffff))),
    ),
  ];

  List<DataRow> dataRows = [];
  List<OrderEntity> orderList = [];
  int pageIndex = 1;
  bool _loading = false;
  ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      var dis = _scrollController.position.maxScrollExtent -
          _scrollController.position.pixels;
      //当距离底部不足300时加载更多
      if (dis < 300 && !_loading) {
        _loadData(loadMore: true);
      }
    });
    _loadData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xff140c3d),
      appBar: AppBar(
        backgroundColor: Color(0xff140c3d),
        centerTitle: true,
        leading: GestureDetector(
          child: Icon(
            Icons.arrow_back_ios,
            size: SizeUtil.px(32),
            color: Color(0xfff3f3f3),
          ),
          onTap: () {
            Navigator.pop(context);
          },
        ),
        title: Text(
          '订单',
          style: TextStyle(fontSize: SizeUtil.px(32), color: Color(0xfff5f5f5)),
        ),
      ),
      body: SingleChildScrollView(
          scrollDirection: Axis.horizontal,
          child: SingleChildScrollView(
            child: DataTable(
              columns: dataColumns,
              rows: dataRows,
            ),
          )),
    );
  }

  _loadData({loadMore = false}) async {
    _loading = true;
    if (!loadMore) {
      pageIndex = 1;
    }
    var currentIndex = pageIndex + (loadMore ? 1 : 0);
    print('loading:currentIndex:$currentIndex');
    try {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      String appToken = prefs.getString('app-token');
      BaseRequest request = OrderListReuqest();
      request
          .add('page', currentIndex)
          .add('limit', 30)
          .addHeader('usertoken', appToken);
      var result = await HiNet.getInstance().fire(request);
      if (result['code'] == -1) {
        TxUtils.showErrorToast('登录失效，请重新登录', context);
        Navigator.pop(context);
        Navigator.of(context).push(MaterialPageRoute(
          builder: (context) {
            return LoginPage(
              arguments: {'loginCode': '-1'},
            );
          },
        ));
      } else if (result['code'] == 0) {
        List<Map<String, dynamic>> listMap =
            new List<Map<String, dynamic>>.from(result['data']['data']);
        List<OrderEntity> list = List();
        for (int i = 0; i < listMap.length; i++) {
          list.add(OrderEntity.fromJson(listMap[i]));
        }
        setState(() {
          if (loadMore) {
            if (list.isNotEmpty) {
              //合成一个新数组
              orderList = [...orderList, ...list];
              pageIndex++;
            }
          } else {
            orderList = list;
          }
          for (int i = 0; i < orderList.length; i++) {
            List<DataCell> dataCells = [
              DataCell(
                Text(
                  orderList[i].numbering,
                  style: TextStyle(
                      fontSize: SizeUtil.px(24), color: Color(0x80ffffff)),
                ),
              ),
              DataCell(
                Text(
                  orderList[i].giftName,
                  style: TextStyle(
                      fontSize: SizeUtil.px(24), color: Color(0x80ffffff)),
                ),
              ),
              DataCell(
                Text(
                  orderList[i].amount.toString(),
                  style: TextStyle(
                      fontSize: SizeUtil.px(24), color: Color(0x80ffffff)),
                ),
              ),
              DataCell(
                Text(
                  orderList[i].gold.toString(),
                  style: TextStyle(
                      fontSize: SizeUtil.px(24), color: Color(0x80ffffff)),
                ),
              ),
              DataCell(
                Text(
                  orderList[i].typeName,
                  style: TextStyle(
                      fontSize: SizeUtil.px(24), color: Color(0x80ffffff)),
                ),
              ),
              DataCell(
                Text(
                  orderList[i].payeeName,
                  style: TextStyle(
                      fontSize: SizeUtil.px(24), color: Color(0x80ffffff)),
                ),
              ),
              DataCell(
                Text(
                  orderList[i].statusName,
                  style: TextStyle(
                      fontSize: SizeUtil.px(24), color: Color(0x80ffffff)),
                ),
              ),
            ];
            DataRow dataRow = DataRow(cells: dataCells);
            dataRows.add(dataRow);
          }
        });
        Future.delayed(Duration(milliseconds: 1000), () {
          _loading = false;
        });
      }
    } on NeedAuth catch (e) {
      print(e);
    } on HiNetError catch (e) {
      print(e);
    }
  }
}
